package com.pig4cloud.pigx.common.security.resource.component;

import com.pig4cloud.pigx.common.security.constant.SecurityConstants;
import com.pig4cloud.pigx.common.security.resource.annotation.EnablePigxResourceServer;
import com.pig4cloud.pigx.common.security.resource.component.beanDefinitionRegistrar.PigxLocalResourceServerConfigurerAdapter;
import com.pig4cloud.pigx.common.security.resource.component.beanDefinitionRegistrar.PigxResourceServerConfigurerAdapter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.type.AnnotationMetadata;

/**
 * @description:
 * @Author 兔子不吃窝边曹
 * @create 2022/8/5 15:46
 **/
@Slf4j
public class PigxSecurityBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar {

    /**
     * 根据注解值动态注入资源服务器的相关属性
     *
     * @param metadata 注解信息
     * @param registry 注册器
     */
    @Override
    public void registerBeanDefinitions(AnnotationMetadata metadata, BeanDefinitionRegistry registry) {
        if (registry.isBeanNameInUse(SecurityConstants.RESOURCE_SERVER_CONFIGURER)) {
            log.info("本地存在资源服务器配置，覆盖默认配置:" + SecurityConstants.RESOURCE_SERVER_CONFIGURER);
            return;
        }

        GenericBeanDefinition beanDefinition = new GenericBeanDefinition();

        Boolean isLocal = (Boolean) metadata.getAnnotationAttributes(EnablePigxResourceServer.class.getName())
                .get("isLocal");
        // 如果是本地模式
        if (isLocal) {
            beanDefinition.setBeanClass(PigxLocalResourceServerConfigurerAdapter.class);
        } else {
            beanDefinition.setBeanClass(PigxResourceServerConfigurerAdapter.class);
        }

        registry.registerBeanDefinition(SecurityConstants.RESOURCE_SERVER_CONFIGURER, beanDefinition);

    }

}

